/**
 * Created by Administrator on 2015/1/26.
 */

var XHR = {
	/**
	 * 从服务端获取服务列表
	 * @param hash
	 * @param type
	 *   ** EVENT_SUBSCRIBE 关注时回复 欢迎信息
	 *   ** DEFAULT         默认默认回复 指定系统不知道该如何回复粉丝的消息时，发送的默认消息
	 * @param config
	 */
	getReply : function(hash,type,config){
		var fn = new Function;
		var config = config || config;
		if(!hash){
			console && console.log("缺省hash");
			return false;
		}
		if(!type){
			console && console.log("缺省hash");
			return false;
		}
		type = type.toUpperCase();
		var loading = config.loading || fn;
		var removeLoading = config.removeLoading || fn;
		var success = config.success || fn;
		var fail = config.fail || fn;
		var timeout = config.timeout || fn;
		var error = config.error || fn;
		$.ajax({
			url : WXB.URLS.api,
			type : "GET",
			dataType : "JSON",
			timeout : WXB.AJAX_TIMEOUT,
			data : {
				"action" : "GetSpecialResp",
				hash : hash,
				key : type
			},
			beforeSend : function(){ loading()},
			success : function(res){
				removeLoading();
				if(res && res.status == "ok"){
					success(res);
				}else if( res && res.status == "fail"){
					fail(res);
				}else{
					error();
				}
			},
			error : function(xhr,txt){
				removeLoading();
				if(txt == "timeout"){
					timeout();
				}else{
					error();
				}
			}
		})
	},
	submit : {
		/**
		 * 提交保存--默认回复
		 * @param hash
		 * @param response 默认回复的内容
		 * @param config
		 */
		"DEFAULT" : function(hash,response,config){
			var fn = new Function;
			var config = config || {};
			var loading = config.loading || fn;
			var removeLoading = config.removeLoading || fn;
			var success = config.success || fn;
			var fail = config.fail || fn;
			var timeout = config.timeout || fn;
			var error = config.error || fn;
			var serverError = config.serverError || fn;
			if(!hash){
				error("缺省hash");
				return false;
			}
			if(!response){
				error("回复内容不能为空");
				return false;
			}
			$.ajax({
				url : WXB.URLS.api,
				type : "POST",
				dataType : "JSON",
				data : {"action":"SetKeyWord","hash":hash,"keyword":"DEFAULT","response":response},
				timeout : WXB.AJAX_TIMEOUT,
				beforeSend : function(){loading();},
				success : function(res){
					removeLoading();
					if(res && res.status == "ok"){
						success(res);
					}else if(res && res.status == "fail"){
						fail(res);
					}else{
						serverError();
					}
				},
				error : function(xhr,txt){
					removeLoading();
					if(txt == "timeout"){
						timeout();
					}else{
						serverError();
					}
				}
			})
		},
		/**
		 * 提交保存--欢迎消息--纯文字
		 * @param hash
		 * @param response
		 * @param config
		 */
		"EVENT_SUBSCRIBE_TEXT" : function(hash,response,config){
			var fn = new Function;
			var config = config || {};
			var loading = config.loading || fn;
			var removeLoading = config.removeLoading || fn;
			var success = config.success || fn;
			var fail = config.fail || fn;
			var error = config.error || fn;
			var timeout = config.timeout || fn;
			var serverError = config.serverError || fn;
			if(!hash){
				error("缺省hash");
				return false;
			}
			if(!response){
				error("回复内容不能为空");
				return false;
			}
			$.ajax({
				url : WXB.URLS.api,
				//url : "http://www.12301.cc/call/pppp.php",
				type : "POST",
				dataType : "JSON",
				data : {"action":"SetKeyWord","hash":hash,"keyword":"EVENT_SUBSCRIBE","response":response},
				timeout : WXB.AJAX_TIMEOUT,
				beforeSend : function(){loading();},
				success : function(res){
					removeLoading();
					if(res && res.status == "ok"){
						success(res);
					}else if(res && res.status == "fail"){
						fail(res);
					}else{
						serverError();
					}
				},
				error : function(xhr,txt){
					removeLoading();
					if(txt == "timeout"){
						timeout();
					}else{
						serverError();
					}
				}
			})
		},
		/**
		 * 提交保存--欢迎消息--图文
		 * @param hash
		 * @param data
		 * @param config
		 */
		"EVENT_SUBSCRIBE_IMG_TEXT" : function(hash,data,config){

			var fn = new Function;
			var config = config || {};
			var loading = config.loading || fn;
			var removeLoading = config.removeLoading || fn;
			var success = config.success || fn;
			var fail = config.fail || fn;
			var timeout = config.timeout || fn;
			var error = config.error || fn; //所传参数不符合要求时
			var serverError = config.serverError || fn;
			//要传递的参数
			var data = data || {};
			
			var title = $.trim(data.title);
			var username = $.trim(data.username);
			var digest = $.trim(data.digest);         //摘要
			var img = data.img;               //封面图片地址
			var source_url = data.source_url; //图片源
			var ue = UE.getEditor('content');
			var txt_content = ue.getContent();//富文本框
			if(!hash){
				error("缺省hash");
				return false;
			}
			if(!title){
				error("标题不能为空");
				return false;
			}
			if(!username){
				error("作者不能为空");
				return false;
			}
			if(!txt_content){
				error("正文不能为空");
				return false;
			}
			if(title.length>30){
				error("标题不能超过30字");
				return false;
			}
			if(!digest){
				error("摘要不能为空");
				return false;
			}
			if(digest.length>100){
				error("摘要不能超过100字");
				return false;
			}
			$.ajax({
				url : WXB.URLS.api,
				//url : "http://www.12301.cc/call/pppp.php",
				type : "POST",
				dataType : "JSON",
				data : {
					"hash" : hash,
					"keyword" : "EVENT_SUBSCRIBE",
					"msg_type" : "IMAGE",
					"action":"SetKeyWord",
					"title" : title,
					"username" : username,
					"digest" : digest,
					"img" : img,
					"txt_msg" : txt_content,
					"source_url" : source_url
				},
				timeout : WXB.AJAX_TIMEOUT,
				beforeSend : function(){loading();},
				success : function(res){
					removeLoading();
					if(res && res.status == "ok"){
						success(res);
					}else if(res && res.status == "fail"){
						fail(res);
					}else{
						serverError();
					}
				},
				error : function(xhr,txt){
					removeLoading();
					if(txt == "timeout"){
						timeout();
					}else{
						serverError();
					}
				}
			})
		}
	}
};

var ImgUpload = (function(){

	function onFileChange(inpFile){
		var path = inpFile.value;
		path = path.replace(/c:\\fakepath\\/gi,"");
		path.replace(/c:/ig,"");
		$("#imgUpload_fileVal").val(path);
	}
	function upload(){
		$("#image-container").hide();
		onloading();
		$("#imgUpload_form").submit();
	}
	function onloading(){
		var imgname = $("#imgUpload_fileVal").val();
		var loadingImg = "http://www.12301.cc/images/other/loading_1.gif";
		var html = '<div class="uploadResult loading"><div class="con"><img src="'+loadingImg+'"/><span class="text">正在上传图片...</span></div></div>';
		$("#uploadFailTip").hide();
		$("#uploadResultCon").html(html);
	}
	function onload(data){ //上传图片完成
		console && console.log("上传图片完成，未知是否成功");
		if(data.status == "ok" && data.key){
			console && console.log("上传图片成功");
			onSuccess(data);
		}else{
			console && console.log("上传图片失败");
			onFail(data)
		}
	}
	function onSuccess(data){
		var path = data.key;
		var html = '<div class="uploadResult success"><div class="con"><img src="'+path+'"/></div></div>';
		$("#uploadResultCon").html(html);
		$("#showimgPathInp").val(path);
		WXB.G.Alert("success",'<p style="width:150px;">上传图片成功</p>',2000)
	}
	function onFail(data){
		var img = '<img src="http://www.12301.cc/wx_public/images/nopic.jpg"  class="img-responsive img-thumbnail" width="150">';
		$("#uploadResultCon").html(img);
		$("#uploadFailTip").show();
		WXB.G.Alert("fail",'<p style="width:150px;">上传图片失败</p>')
	}

	return{
		onFileChange : onFileChange,
		upload : upload,
		onload : onload
	}

})();

var Reply = (function(){

	function get(type){
		var type = type.toUpperCase() || "EVENT_SUBSCRIBE";
		var FIX = type == "EVENT_SUBSCRIBE" ? "欢迎信息" : "默认回复";
		var failTxt = "获取" + FIX +"失败，请稍后重试";
		var timeoutTxt = "获取" + FIX +"超时，请稍后重试";
		var errorTxt = "获取" + FIX +"出错，请稍后重试";
		var hash = WXB.G.SwitchAccount.getHash();
		if(!hash){
			console && console.log("缺省hash");
			return false;
		}
		XHR.getReply(hash,type,{
			loading : function(){},
			removeLoading : function(){},
			success : function(res){
				var dtype = res.list.type;
				if(dtype == "TEXT"){ //欢迎消息--文本消息
					if(type == "EVENT_SUBSCRIBE"){
						$("#reply_msg_textarea").val(res.list.digest);
					}else{
						$("#reply_default_textarea").val(res.list.digest);
					}
				}else if(dtype == "IMGAGE"){//欢迎消息--图文消息
					$("#reply_welcome_imgtxt_tit").val(res.list.title);
					$("#reply_username_imgtxt_tit").val(res.list.username);
					$("#showimgPathInp").val(res.list.picUrl);
					$("#reply_welcome_imgtxt_digest").val(res.list.digest);
					$("#reply_welcome_imgtxt_ourl").val(res.list.url);
				}
			},
			fail : function(res){
				alert(failTxt);
			},
			timeout : function(){
				alert(timeoutTxt);
			},
			error : function(){
				alert(errorTxt);
			}
		})
	}

	return{
		get : get
	}

})();


$(function(){
	WXB.G.SwitchAccount.init(function(){
		$("#tabNavWrap").on("click",".tabNav",function(e){
			var target = $(e.currentTarget);
			var index = target.index();
			target.addClass("active").siblings().removeClass("active");
			$("#tabConWrap > .tabPanel").hide().eq(index).show();
		})
		$("#welSwitchTabNavWrap").on("click",".welTabNav",function(e){
			var target = $(e.currentTarget);
			var index = target.index();
			$(".welPanel").hide().eq(index).show();
		})
		$("#openDialogBtn").on("click",function(e){
			$("#image-container").show();
		})
		/**
		 * 关闭上传图片弹窗
		 */
		$("#image-container").on("click","#cancelImgDialogBtn,#closeImgDialogBtn",function(e){
			$("#image-container").hide();
		})
		$("#image-container").on("click","#imgDialog-tabNavCon > li",function(e){
			var target = $(e.currentTarget);
			var index = target.index();
			var panels = $("#imgDialog-tabPanCon").children();
			target.addClass("active").siblings().removeClass("active");
			if(index>-1) panels.eq(index).show().siblings().hide();
		});
		/**
		 * 选择图片弹窗-确认按钮
		 */
		$("#submitImgUploadBtn").on("click",function(e){
			var active = $("#imgDialog-tabNavCon").children(".active");
			if(active.hasClass("upload")){
				ImgUpload.upload();
			}else{
				var url = $("#imgUpload_space_inpFile").val();
				$("#showimgPathInp").val(url);
				$("#image-container").hide();
			}
		})
		$("#imgUpload_inpFile").on("change",function(e){
			ImgUpload.onFileChange(e.currentTarget);
		})
		$("#tabNavWrap").children(":first").trigger("click");
		//提交欢迎信息
		$("#submitBtn_welcome").on("click",function(){
			var radio = $("#welSwitchTabNavWrap").find("input:radio:checked");
			var value = radio.val();
			var hash = WXB.G.SwitchAccount.getHash();
			var response = $("#reply_msg_textarea").val();//微信发送文本信息  <新建>
			if(value == "IMAGE"){ //提交图文欢迎消息
				var title = $("#reply_welcome_imgtxt_tit").val();
				var username = $("#reply_username_imgtxt_tit").val();
				var digest = $("#reply_welcome_imgtxt_digest").val();
				var img = $("#showimgPathInp").val();
				var source_url = $("#reply_welcome_imgtxt_ourl").val();
				XHR.submit.EVENT_SUBSCRIBE_IMG_TEXT(hash,{
					title : title,
					username : username,
					digest : digest,
					img : img,
					source_url : source_url
				},{
					loading : function(){$("#welcome_loading").show()},
					removeLoading : function(){$("#welcome_loading").hide()},
					success : function(res){
						WXB.G.Alert("success",'<p style="wdith:160px">保存成功！</p>');
						window.location.reload();
					},
					fail : function(res){
						alert(res.msg);
					},
					error : function(msg){
						alert(msg)
					},
					timeout : function(){
						alert("请求超时请稍后重试");
					},
					serverError : function(){
						alert("请求出错请稍后重试");
					}
				})
			}else{ //提交纯文本欢迎消息
				XHR.submit.EVENT_SUBSCRIBE_TEXT(hash,response,{
					loading : function(){$("#welcome_loading").show()},
					removeLoading : function(){$("#welcome_loading").hide()},
					error : function(msg){ //校验不通过时
						alert(msg);
					},
					success : function(res){
						WXB.G.Alert("success",'<p style="wdith:160px">保存成功！</p>');
						window.location.reload();
					},
					fail : function(res){
						alert(res.msg);
					},
					timeout : function(){
						alert("请求超时请稍后重试");
					},
					serverError : function(){
						alert("请求出错请稍后重试");
					}
				})
			}
		});
		//提交默认回复信息
		$("#submitBtn_defaultReply").on("click",function(){
			var response = $("#reply_default_textarea").val();
			var hash = WXB.G.SwitchAccount.getHash();
			XHR.submit.DEFAULT(hash,response,{
				loading : function(){$("#submit_default_loading").show()},
				removeLoading : function(){$("#submit_default_loading").hide()},
				error : function(msg){ //校验不通过时
					alert(msg);
				},
				success : function(res){
					WXB.G.Alert("success",'<p style="wdith:160px">保存成功！</p>');
					window.location.reload();
				},
				fail : function(res){
					alert(res.msg);
				},
				timeout : function(){
					alert("请求超时请稍后重试");
				},
				error : function(){
					alert("请求出错请稍后重试");
				}
			})
		});
		WXB.G.SwitchAccount.on("change",function(data){
			Reply.get("EVENT_SUBSCRIBE");
			Reply.get("DEFAULT");
		})
		Reply.get("EVENT_SUBSCRIBE");
		Reply.get("DEFAULT");



	});
})







